package com.chuangyang.fixboxmaster.ui.fragment.home;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chuangyang.fixboxlib.widgets.MultiSwipeRefreshLayout;
import com.chuangyang.fixboxlib.widgets.SlidingTabLayout;
import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.ui.fragment.BaseFragment;

import java.util.ArrayList;

public class BaseHomeFragment extends BaseFragment implements MultiSwipeRefreshLayout.CanChildScrollUpCallback {

    private View mContentView;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private ArrayList<HomeFragment> mFragments = new ArrayList<>();
    private int mSelectPosition;
    ViewPagerAdapter mAdapter;
    private String [] mTitle= new String [] {"待付款","处理中","已完成","已取消"};

    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_base_home_list, container, false);
        trySetupSwipeRefresh();
        updateSwipeRefreshProgressBarTop();
        initView();
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    public static BaseHomeFragment newInstance() {
        return new BaseHomeFragment();
    }

    private void initView(){
        ViewPager mViewPager = (ViewPager) mContentView.findViewById(R.id.viewPager);
        mAdapter = new ViewPagerAdapter(getChildFragmentManager());
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(mTitle.length);
        mViewPager.setCurrentItem(0);
        SlidingTabLayout mSlidingTabLayout = (SlidingTabLayout) mContentView.findViewById(R.id.sliding_tabs);
        mSlidingTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);
        mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.tab_selected_strip2));
        mSlidingTabLayout.setDistributeEvenly(true);
        mSlidingTabLayout.setViewPager(mViewPager);
        mSlidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mSelectPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                enableDisableSwipeRefresh(state == ViewPager.SCROLL_STATE_IDLE);
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setContentView(mContentView);
        setHasOptionsMenu(true);
        showResult();
    }


    @Override
    public boolean canSwipeRefreshChildScrollUp() {
        for (int i = 0; i < mFragments.size(); i++) {
            if (!mFragments.get(i).getUserVisibleHint()) {
                continue;
            }
            return ViewCompat.canScrollVertically(mFragments.get(i).getListView(), -1);
        }
        return false;
    }


    public class ViewPagerAdapter extends FragmentPagerAdapter {
        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            HomeFragment homeFragment = new HomeFragment();
            homeFragment.setStatus(mTitle[position]);
            mFragments.add(homeFragment);
            return homeFragment;
        }

        @Override
        public int getCount() {
            return mTitle.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return  mTitle[position];
        }
    }


    private void trySetupSwipeRefresh() {
        mSwipeRefreshLayout = (SwipeRefreshLayout) mContentView.findViewById(R.id.swipe_refresh_layout);
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setColorSchemeResources(
                    R.color.refresh_progress_1,
                    R.color.refresh_progress_2,
                    R.color.refresh_progress_3);
            mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    requestDataRefresh();
                }
            });
            if (mSwipeRefreshLayout instanceof MultiSwipeRefreshLayout) {
                MultiSwipeRefreshLayout mswrl = (MultiSwipeRefreshLayout) mSwipeRefreshLayout;
                mswrl.setCanChildScrollUpCallback(this);
            }
        }
    }

    private void updateSwipeRefreshProgressBarTop() {
        if (mSwipeRefreshLayout == null) {
            return;
        }
        int progressBarStartMargin = getResources().getDimensionPixelSize(
                R.dimen.swipe_refresh_progress_bar_start_margin);
        int progressBarEndMargin = getResources().getDimensionPixelSize(
                R.dimen.swipe_refresh_progress_bar_end_margin);
        mSwipeRefreshLayout.setProgressViewOffset(false,
                progressBarStartMargin, progressBarEndMargin);
    }


    protected void requestDataRefresh() {
        for (int i = 0; i < mFragments.size(); i++) {
            if (mFragments.get(i).getUserVisibleHint()) {
                (mFragments.get(i)).updateListView();
            }
        }
        onRefreshingStateChanged(false, 1000);
    }



    protected void onRefreshingStateChanged(final boolean refreshing, long delayMillis) {
        if (mSwipeRefreshLayout != null) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(refreshing);
                }
            }, delayMillis);
        }
    }

    protected void enableDisableSwipeRefresh(boolean enable) {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setEnabled(enable);
        }
    }
}

